package com.codi.api.controller.v2;

import com.codi.api.security.UserUtil;
import com.codi.api.validation.QueryValidation;
import com.codi.base.log.annotation.Loggable;
import com.codi.base.util.EqualsUtil;
import com.codi.base.util.StringUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.domain.FundCombination;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.domain.UserBank;
import com.codi.bus.core.resultModel.*;
import com.codi.bus.core.service.*;
import com.codi.bus.core.service.model.PortfolioModel;
import com.codi.bus.core.service.model.PortfolioTradeModel;
import com.codi.fcloud.ufx.hssale.query.AccountBankQuery;
import com.codi.message.util.MessageUtil;
import com.codi.trade.dto.HsAccoBankQueryDto;
import com.codi.trade.response.HsAccoBankQueryResponse;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 查询v2
 *
 * @author Shangdu Lin
 * @date 2016年12月14日
 */
@Slf4j
@Controller
@RequestMapping("/query/v2")
public class QueryControllerV2 {


    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "queryService")
    private QueryService queryService;

    @Autowired
    private QueryValidation queryValidation;

    @Resource(name = "fundInfoService")
    private FundInfoService fundInfoService;

    @Autowired
    private FundCombinationService fundCombinationService;

    @Autowired
    private AccountBankQuery accountBankQuery;

    @Autowired
    private BankService bankService;

    /**
     * 查询交易记录，过滤掉T0基金
     *
     * @param token
     * @param requestNum
     * @param queryFlag
     * @param beginNum
     * @param sortDirection
     * @param deviceId
     */
    @RequestMapping(value = "/applys", method = RequestMethod.GET)
    @ResponseBody
    @Loggable
    public BaseResult applyQuery(@RequestParam String token,
                                 @RequestParam Integer requestNum,
                                 @RequestParam Integer queryFlag,
                                 @RequestParam Integer beginNum,
                                 @RequestParam String sortDirection,
                                 @RequestHeader(value = GlobalConstant.HEADER_APP_DEVICE) String deviceId) {
        ApplyListResult result = null;
        // 验证token
        ValidateTokenResult validateTokenResult = userService.validateToken(token, deviceId);
        if (!validateTokenResult.getSuccess()) {
            String errorMessage = MessageUtil.getErrorMessage(validateTokenResult.getErrorCode(), null);
            validateTokenResult.setErrorMessage(errorMessage);
            return validateTokenResult;
        }

        result = queryService.queryApplys(validateTokenResult.getUserId(), requestNum, queryFlag, beginNum,
            sortDirection, true);
        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }

        return result;
    }

    /**
     * 组合交易记录
     *
     * @param token
     * @param requestNum
     * @param queryFlag
     * @param beginNum
     * @param sortDirection
     * @param deviceId
     */
    @RequestMapping(value = "/portfolioApplys", method = RequestMethod.GET)
    @ResponseBody
    @Loggable
    public BaseResult portfolioApply(@RequestParam String token,
                                     @RequestParam Integer requestNum,
                                     @RequestParam Integer queryFlag,
                                     @RequestParam Integer beginNum,
                                     @RequestParam String sortDirection,
                                     @RequestHeader(value = GlobalConstant.HEADER_APP_DEVICE) String deviceId) {
        PortfolioApplyListResult result = null;
        // 验证token
        ValidateTokenResult validateTokenResult = userService.validateToken(token, deviceId);
        if (!validateTokenResult.getSuccess()) {
            String errorMessage = MessageUtil.getErrorMessage(validateTokenResult.getErrorCode(), null);
            validateTokenResult.setErrorMessage(errorMessage);
            return validateTokenResult;
        }

        result = queryService.queryPortfolioApplys(validateTokenResult.getUserId(), requestNum, queryFlag, beginNum,
            sortDirection, true);
        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }

        return result;
    }

    /**
     * 查询资产，过滤掉T0基金和组合
     *
     * @param token
     * @param requestNum
     * @param queryFlag
     * @param beginNum
     * @param sortDirection
     * @param deviceId
     */
    @RequestMapping(value = "/shares", method = RequestMethod.GET)
    @ResponseBody
    @Loggable
    public BaseResult shareQuery(@RequestParam String token,
                                 @RequestParam Integer requestNum,
                                 @RequestParam Integer queryFlag,
                                 @RequestParam Integer beginNum,
                                 @RequestParam String sortDirection,
                                 @RequestHeader(value = GlobalConstant.HEADER_APP_DEVICE) String deviceId) {

        ShareListResult result = null;
        // 验证token
        ValidateTokenResult validateTokenResult = userService.validateToken(token, deviceId);
        if (!validateTokenResult.getSuccess()) {
            String errorMessage = MessageUtil.getErrorMessage(validateTokenResult.getErrorCode(), null);
            validateTokenResult.setErrorMessage(errorMessage);

            return validateTokenResult;
        }

        // 验证输入
        result = queryValidation.validateShareQuery(requestNum);
        if (result != null) {
            return result;
        }

        result = queryService.querySharesWithoutPort(validateTokenResult.getUserId(), requestNum, queryFlag, beginNum,
            sortDirection, true);
        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }

        return result;
    }

    /**
     * 查询组合列表信息
     */
    @RequestMapping(value = "/portfolio", method = RequestMethod.GET)
    @ResponseBody
    @Loggable
    public BaseResult queryProtfolio(@RequestParam String token,
                                     @RequestHeader(value = GlobalConstant.HEADER_APP_DEVICE) String deviceId) {

        AssetsPortfolioResult assetsPortfolioResult = new AssetsPortfolioResult();
        // 验证token
        ValidateTokenResult validateTokenResult = userService.validateToken(token, deviceId);
        if (!validateTokenResult.getSuccess()) {
            String errorMessage = MessageUtil.getErrorMessage(validateTokenResult.getErrorCode(), null);
            validateTokenResult.setErrorMessage(errorMessage);

            return validateTokenResult;
        }

        assetsPortfolioResult = queryService.queryPortfolioAssets(validateTokenResult.getUserId());


        return assetsPortfolioResult;
    }

    /**
     * 查询组合具体基金信息
     */
    @RequestMapping(value = "/portfolioFunds", method = RequestMethod.GET)
    @ResponseBody
    @Loggable
    public BaseResult queryProtfolioFunds(@RequestParam String token,
                                          @RequestHeader(value = GlobalConstant.HEADER_APP_DEVICE) String deviceId,
                                          @RequestParam String portfolioCode) {

        PortfolioModel result = new PortfolioModel();
        // 验证token
        ValidateTokenResult validateTokenResult = userService.validateToken(token, deviceId);
        if (!validateTokenResult.getSuccess()) {
            String errorMessage = MessageUtil.getErrorMessage(validateTokenResult.getErrorCode(), null);
            validateTokenResult.setErrorMessage(errorMessage);

            return validateTokenResult;
        }

        result = queryService.queryPortfolioFunds(validateTokenResult.getUserId(), portfolioCode);
        FundCombination fundCombination = fundCombinationService.queryOne(portfolioCode);
        if (fundCombination != null && fundCombination.getAnnualizedIncome() != null) {
            result.setShare("向您推荐一只基金组合，组合年化收益率为" + fundCombination.getAnnualizedIncome().toString() + "%");
        } else {
            result.setShare("向您推荐一只基金组合");
        }

        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }


        // spy 2017-12-13 10:45:00
        if (result != null && result.getPortfolioTrades() != null) {

            // 查询用户银行卡列表
            User user = userService.getUser(validateTokenResult.getUserId());

            if (Strings.isNullOrEmpty(user.getExternalClientId())) {
                return result;
            }

            HsAccoBankQueryDto queryDto = HsAccoBankQueryDto.builder()
                .client_id(user.getExternalClientId())
                .build();

            List<HsAccoBankQueryResponse> hsBanks = accountBankQuery.query(queryDto);

            if (hsBanks != null) {
                List<PortfolioTradeModel> portfolioTrades = result.getPortfolioTrades();
                portfolioTrades.forEach(item -> {

                    String portfolioTradeAcco = item.getTradeAcco();

                    for (HsAccoBankQueryResponse queryResponse : hsBanks) {

                        if (EqualsUtil.equals(portfolioTradeAcco, queryResponse.getTrade_acco())) {

                            List<UserBank> userBanks = bankService.getBanks(user.getUserId(), queryResponse.getBank_account());

                            if (userBanks == null || userBanks.isEmpty()) {
                                log.warn("userId={},bankNo={}不存在", user.getUserId(), queryResponse.getBank_account());
                            } else {
                                UserBank userBank = new UserBank();
                                if (!GlobalConstant.CAPITAL_MODE_COUNTER.equals(userBanks.get(0).getCapitalMode())) {
                                    userBank = userBanks.get(0);
                                } else {
                                    userBank = userBanks.get(1);
                                }
                                item.setUserBankNo(userBank.getUserBankNo());
                                item.setBankCode(userBank.getBankCode());
                                item.setBankName(userBank.getBankName());
                                item.setBranchBank(userBank.getBranchbank() == null ? "" : userBank.getBranchbank());
                                item.setBranchBankName(userBank.getBankBranchName() == null ? "" : userBank.getBankBranchName());
                                item.setCapitalMode(userBank.getCapitalMode());
                            }
                            break;
                        }
                    }


                });
            } else {
                log.warn("没有该账户对应的银行卡交易账号信息");
            }
        }


        return result;
    }

    /**
     * 查询基金基本信息
     *
     * @param keyword
     * @throws Exception
     */
    @Loggable
    @RequestMapping("/fundInfos")
    @ResponseBody
    public BaseResult queryFundInfo(@RequestParam String keyword) throws Exception {
        // 查询基金
        FundInfoListResult result = fundInfoService.query(keyword, UserUtil.getLoginUserId());

        return result;
    }

//    /**
//     * 用来改地名
//     */
//    @RequestMapping(value = "/changePlace", method = RequestMethod.GET)
//    @ResponseBody
//    @Loggable
//    public BaseResult changePlace(){
//        return queryService.changePlace();
//    }

    /**
     * 查询交易记录，过滤掉T0基金
     *
     * @param token
     * @param requestNum
     * @param queryFlag
     * @param beginNum
     * @param sortDirection
     * @param deviceId
     */
    @RequestMapping(value = "/applysall", method = RequestMethod.GET)
    @ResponseBody
    @Loggable
    public BaseResult applysall(@RequestParam String token,
                                @RequestParam(defaultValue = "100") Integer requestNum,
                                @RequestParam(defaultValue = "1") Integer queryFlag,
                                @RequestParam(defaultValue = "1") Integer beginNum,
                                @RequestParam(defaultValue = "1") String sortDirection,
                                @RequestHeader(value = GlobalConstant.HEADER_APP_DEVICE) String deviceId) {
        ApplyListResult result = null;
        // 验证token
        ValidateTokenResult validateTokenResult = userService.validateToken(token, deviceId);
        if (!validateTokenResult.getSuccess()) {
            String errorMessage = MessageUtil.getErrorMessage(validateTokenResult.getErrorCode(), null);
            validateTokenResult.setErrorMessage(errorMessage);
            return validateTokenResult;
        }

        result = queryService.queryApplys(validateTokenResult.getUserId(), requestNum, queryFlag, beginNum,
            sortDirection, false);
        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }

        return result;
    }

    @Loggable
    @RequestMapping(value = "/shareNew", method = RequestMethod.GET)
    @ResponseBody
    public BaseResult assetsQuery() {

        AssetsResult result = null;


        result = queryService.queryFundAssets(UserUtil.getLoginUserId());
        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }

        return result;
    }

    /**
     * 查询单个资产
     */
    @RequestMapping(value = "/fundshare", method = RequestMethod.GET)
    @ResponseBody
    @Loggable
    public BaseResult shareQuery(String fundCode) {

        BaseResult result = null;


        result = queryService.queryFundShares(UserUtil.getLoginUserId(), true, fundCode);
        if (result.getSuccess() == false && StringUtil.isEmpty(result.getErrorMessage())) {
            result.setErrorMessage(MessageUtil.getErrorMessage(result.getErrorCode(), null));
        }

        return result;
    }

}
